package com.quan.system.web.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.quan.base.common.base.web.support.BaseResult;
import com.quan.base.common.base.web.support.controller.BaseController;
import com.quan.base.common.exception.BizException;
import com.quan.base.common.utils.Paginator;
import com.quan.oss.aliyun.client.AliyunOSSClient;
import com.quan.oss.common.ResponseMsg;
import com.quan.oss.common.aliyun.OSSBucket;
import com.quan.oss.qiniu.client.QiniuOSSClient;
import com.quan.system.common.enums.OSS;
import com.quan.system.rpc.api.SysOssService;
import com.quan.system.rpc.model.SysOss;
import com.quan.upms.annotation.RequiresPermissions;


@RestController
@RequestMapping(value = "/api/system/oss")
public class SysOssController extends BaseController {

	@Autowired
	private SysOssService sysOssService;
	
	@Autowired
	private AliyunOSSClient aliyunOSSClient;
	
	@Autowired
	private QiniuOSSClient qiniuOSSClient;
	
	@RequiresPermissions(value="system:oss:delete", description="删除文件")
	@GetMapping(value = "/delete/{id}")
	public Object delete(@PathVariable Integer id) {
		try {
			SysOss oss = this.sysOssService.selectById(id) ;
			
			if(oss.getOss().equals(OSS.QINIUYUN.getName())) { //删除七牛云上的文件
				this.qiniuOSSClient.delete(oss.getBucketName(), oss.getFname()) ;
			} else if(oss.getOss().equals(OSS.ALIYUN.getName())) { //删除阿里云上的文件
				this.aliyunOSSClient.delete(oss.getBucketName(), oss.getFname());
			}
			this.sysOssService.delete(id) ;
			return BaseResult.ok();
		} catch (BizException e) {
			return BaseResult.failure("删除文件失败") ;
		}
	}

	@RequiresPermissions(value="system:oss:delete", description="删除文件")
	@GetMapping(value = "/deleteBatch")
	public Object deleteBatch(String ids) {
		try {
			String[] split = ids.split(",");
			for (String id : split) {
				SysOss oss = this.sysOssService.selectById(Integer.parseInt(id)) ;
				
				if(oss.getOss().equals(OSS.QINIUYUN.getName())) { //删除七牛云上的文件
					this.qiniuOSSClient.delete(oss.getBucketName(), oss.getFname()) ;
				} else if(oss.getOss().equals(OSS.ALIYUN.getName())) { //删除阿里云上的文件
					this.aliyunOSSClient.delete(oss.getBucketName(), oss.getFname());
				}
			}
			this.sysOssService.deleteByIds(ids) ;
			return BaseResult.ok();
		} catch (BizException e) {
			return BaseResult.failure("删除文件失败") ;
		}
	}

	@RequiresPermissions(value="system:oss:detail", description="文件详情")
	@GetMapping(value = "/get/{id}")
	public Object get(@PathVariable Integer id) {
		return this.sysOssService.selectById(id);
	}

	@RequiresPermissions(value="system:oss:list", description="文件列表")
	@GetMapping(value = "/list")
	public Object list(SysOss entity) {
		return this.sysOssService.selectPage(new Paginator(this.request), entity);
	}
	
	@GetMapping(value = "/getBuckets")
	public Object getBuckets(String ossName) {
		if(ossName.equals(OSS.QINIUYUN.getName())) {	//获取七牛云空间列表
			return this.qiniuOSSClient.getBuckets() ;
		} else if(ossName.equals(OSS.ALIYUN.getName())) { //获取阿里云空间列表
			List<String> buckets = new ArrayList<String>() ;
			List<OSSBucket> listBuckets = this.aliyunOSSClient.listBuckets();
			for (OSSBucket ossBucket : listBuckets) {
				buckets.add(ossBucket.getName()) ;
			}
			return buckets ;
		} else {
			return BaseResult.failure("找不到对应的OSS供应商") ;
		}
	}
	
	@RequiresPermissions(value="system:oss:upload", description="文件上传")
	@PostMapping(value = "/upload")
	public Object upload(HttpServletRequest request, String ossName, String bucketName, String prefixName, String remark) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request ;
		try {
			if(StringUtils.isNotBlank(ossName) && StringUtils.isNotBlank(bucketName)) {
				//取得MultiValueMap集合
				MultiValueMap<String,MultipartFile> multiFileMap = multipartRequest.getMultiFileMap() ;
				Set<Entry<String, List<MultipartFile>>> entrySet = multiFileMap.entrySet() ;
				for (Entry<String, List<MultipartFile>> entry : entrySet) {
					
					//获取MultipartFile集合
					List<MultipartFile> multipartFiles = entry.getValue() ;
					for (MultipartFile multipartFile : multipartFiles) {
						
						
						if(ossName.equals(OSS.QINIUYUN.getName())) { //上传文件到七牛云
							ResponseMsg upload = this.qiniuOSSClient.upload(bucketName, multipartFile.getBytes(), multipartFile.getOriginalFilename(), prefixName) ;
							
							if(null != upload && upload.isStatus()) {
								SysOss entity = new SysOss() ;
								entity.setOss(ossName);
								entity.setBucketName(bucketName);
								entity.setFname(upload.getFname());
								entity.setFsize(multipartFile.getSize());
								entity.setFtype(multipartFile.getContentType());
								entity.setStatus(1);
								entity.setUrl(upload.getUrl());
								entity.setRemarks(remark);
								this.sysOssService.insertSelective(entity) ;
							}
							
							return upload ;
						} else if(ossName.equals(OSS.ALIYUN.getName())) { //上传文件到阿里云
							ResponseMsg upload = this.aliyunOSSClient.upload(bucketName, multipartFile.getBytes(), multipartFile.getOriginalFilename(), prefixName) ;
							
							if(null != upload && upload.isStatus()) {
								SysOss entity = new SysOss() ;
								entity.setOss(ossName);
								entity.setBucketName(bucketName);
								entity.setFname(upload.getFname());
								entity.setFsize(multipartFile.getSize());
								entity.setFtype(multipartFile.getContentType());
								entity.setStatus(1);
								entity.setUrl(upload.getUrl());
								entity.setRemarks(remark);
								this.sysOssService.insertSelective(entity) ;
							}
							
							return upload ;
						} else {
							return BaseResult.failure("找不到对应的OSS供应商") ;
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return BaseResult.failure() ;
	}
	
}
